#include "bsp_tim.h"
#include "cw32l010_btim.h"
#include "cw32l010_sysctrl.h"

void bsp_basicTimer_init(void)
{
    __SYSCTRL_BTIM123_CLK_ENABLE();

    BTIM_TimeBaseInitTypeDef BTIM_TimeBaseInitStruct = {0};

    BTIM_TimeBaseInitStruct.BTIM_CountMode = BTIM_COUNT_MODE_SINGLE;
    BTIM_TimeBaseInitStruct.BTIM_Mode = BTIM_MODE_TIMER;
    BTIM_TimeBaseInitStruct.BTIM_Period = 0xFFFF;
    BTIM_TimeBaseInitStruct.BTIM_Prescaler = 48000;
    BTIM_TimeBaseInit(CW_BTIM1, &BTIM_TimeBaseInitStruct);

    BTIM_ITConfig(CW_BTIM1, BTIM_IT_UPDATE, ENABLE);
    NVIC_EnableIRQ(BTIM1_IRQn);
}

void delay_ms(int ms)
{
    CW_BTIM1->CNT = 0;
    CW_BTIM1->CR1 |= BTIMx_CR1_EN_Msk;
    while (CW_BTIM1->CNT < ms)
    {
    };
    CW_BTIM1->CR1 &= ~BTIMx_CR1_EN_Msk;
}

void BTIM1_IRQHandler(void)
{
    /* USER CODE BEGIN */
    if (BTIM_GetITStatus(CW_BTIM1, BTIM_IT_UPDATE))
    {
        BTIM_ClearITPendingBit(CW_BTIM1, BTIM_IT_UPDATE);
    }
    /* USER CODE END */
}
